package com.xiang.sql.service;

import java.io.File;
import java.io.PrintWriter;
import java.util.List;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiang.api.Util;
import com.xiang.sql.entity.Upload;
import com.xiang.sql.entity.User;
import com.xiang.sql.mapper.UploadMapper;

/**
 * 上传文件 服务实现类
 * 
 * @author mac-xiang
 */
@Service
public class UploadService extends ServiceImpl<UploadMapper, Upload> {
  @Resource
  UploadMapper mapper;

  private QueryWrapper<Upload> readWrapper(JSONObject p, User per) {
    QueryWrapper<Upload> ret = Util.getQuery(p, Upload.class);
    if (per != null && !per.per("文件查询")) {
      ret.eq("`user`", per.id);
    }
    return ret;
  }

  public List<Upload> getList(JSONObject p, User per) {
    return mapper.selectList(readWrapper(p, per));
  }

  public Page<Upload> getPage(Page<Upload> page, JSONObject p, User per) {
    return mapper.selectPage(page == null ? new Page<Upload>(1, 100) : page, readWrapper(p, per));
  }

  public Page<Upload> getPage(JSONObject p, User per) {
    return getPage(null, p, per);
  }

  public Upload create(JSONObject p, User per) {
    try {
      if (per != null && per.per("文件上传")) {
        Upload entity = Util.getEntity(p, Upload.class);
        entity.createTime = null;
        entity.user = per.id;
        mapper.insert(entity);
        return entity;
      }
      throw new RuntimeException("没有权限");
    } catch (Exception e) {
      String path = p.getString("path");
      if (path != null) {
        new File("public/" + path).delete();
      }
      throw new RuntimeException(Util.errString(e));
    }
  }

  public Upload create(String create, String type, String name, String path, String other) {
    Upload entity = new Upload(create, type, name, path, other);
    mapper.insert(entity);
    return entity;
  }

  public int update(JSONObject p, User per) {
    try {
      if (per != null && per.per("文件修改")) {
        Upload entity = Util.getEntity(p, Upload.class);
        QueryWrapper<Upload> qw = Util.getQuery(p.getJSONObject("#where"), Upload.class).eq("id", p.getString("id"));
        entity.user = null;
        return mapper.update(entity, qw);
      }
      throw new RuntimeException("没有权限");
    } catch (Exception e) {
      throw new RuntimeException(Util.errString(e));
    }
  }

  public Object read(JSONObject p, User per) {
    Page<Upload> page = Util.getPage(p, Upload.class);
    return page == null ? getList(p, per) : getPage(page, p, per);
  }

  public int delete(JSONObject p, User per) {
    try {
      if (per != null && per.per("文件删除")) {
        String id = p.getString("id");
        if (id != null) {
          Upload entity = mapper.selectById(id);
          new File("public/" + entity.path).delete();
          return mapper.deleteById(id);
        }
        throw new RuntimeException("删除文件时必须携带id");
      }
      throw new RuntimeException("没有权限");
    } catch (Exception e) {
      throw new RuntimeException(Util.errString(e));
    }
  }

  public long count(JSONObject p, User per) {
    return this.count(readWrapper(p, per));
  }

  public void read(String id, HttpServletRequest request, HttpServletResponse response) {
    Upload f = mapper.selectById(id);
    response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");

    try {
      response.setHeader("content-type", Util.mime(f.path.substring(f.path.lastIndexOf(".") + 1)));
      response.getOutputStream().write(Util.readFile("public/" + f.path));
    } catch (Exception e) {
      try {
        PrintWriter writer = response.getWriter();
        writer.write(f.path);
        writer.close();
      } catch (Exception e2) {
      }
      response.reset();
    }
  }
}
